﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using TY.Utilities;
using CefSharp;
using CefSharp.WinForms;
using CCWin;
using System.Threading;
using System.Threading.Tasks;
using TY_Hoist.WinApp.Code;
using System.Diagnostics;

namespace TY_Hoist.WinApp
{

    public partial class MainCefForm : CCSkinMain
    {
        #region 全局变量
        //CEFSharp对象
        private ChromiumWebBrowser webBrowser = null;
        #endregion
        public MainCefForm()
        {
            var setting = new CefSharp.CefSettings();
            setting.CefCommandLineArgs.Add("--allow-file-access-from-files", "1");
            setting.CefCommandLineArgs.Add("--disable-web-security", "1");
            CefSharp.Cef.Initialize(setting, true, false);
            InitializeComponent();
            StartServer();
        }

        SysControl sysControl;
        RecSuite recSuite;
        FlowForm mainForm;
        Form8 form8;
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        private void MainCefForm_Load(object sender, EventArgs e)
        {
            this.label1.Location = new Point(720, 500);
            webBrowser = new ChromiumWebBrowser(Application.StartupPath + @"\UI\Page\Login.html");

            this.Controls.Add(webBrowser);
            webBrowser.Visible = false;
            webBrowser.FrameLoadEnd += WebBrowser_FrameLoadEnd;

            MyService myService = new MyService(webBrowser);
            myService.InitCameraEvent += MyService_InitCameraEvent;
            myService.ShowCameraEvent += MyService_ShowCameraEvent;
            myService.HideCameraEvent += MyService_HideCameraEvent;
            myService.StartRecordVideoEvent += MyService_StartRecordVideoEvent;
            myService.StopRecordVideoEvent += MyService_StopRecordVideoEvent;
            webBrowser.RegisterAsyncJsObject("myService", myService, false);

            sysControl = new SysControl();
            sysControl.SaveFileDialogEvent += SysControl_SaveFileDialogEvent;
            sysControl.GetVideoPathEvent += SysControl_GetVideoPathEvent;
            sysControl.SaveVideoPathEvent += SysControl_SaveVideoPathEvent;
            sysControl.SelectPathEvent += SysControl_SelectPathEvent;
            sysControl.MoveFormEvent += SysControl_MoveFormEvent;
            sysControl.ShowPanelEvent += SysControl_ShowPanelEvent;
            sysControl.HidePanelEvent += SysControl_HidePanelEvent;
            sysControl.CloseFormEvent += SysControl_CloseFormEvent;
            sysControl.CompletTestEvent += SysControl_CompletTestEvent;
            sysControl.OpenMainEvent += SysControl_OpenMainEvent;
            webBrowser.RegisterJsObject("sysControl", sysControl, false);

        }

        private void SysControl_OpenMainEvent()
        {
            this.BeginInvoke(new Action(() =>
            {
                form8.Close();
                recSuite.Close();
                this.panel1.Visible = true;
                mainForm = new FlowForm();
                mainForm.Dock = DockStyle.Fill;
                mainForm.FormBorderStyle = FormBorderStyle.None;
                mainForm.TopLevel = false;
                this.panel1.Controls.Clear();
                this.panel1.Controls.Add(mainForm);

                mainForm.Show();
            }));
        }

        private string SysControl_CompletTestEvent()
        {
            if (CVVideo.capture == null)
            {
             
                MessageBox.Show(this, "当前状态不能完成试验！");
                return "0";
            }
            else
            {
                return CVVideo.CompletTest();
            }
        }

        private void SysControl_HidePanelEvent()
        {
            this.BeginInvoke(new Action(() =>
            {
                this.panel1.Visible = false;

            }));
        }

        private void SysControl_ShowPanelEvent()
        {
            this.BeginInvoke(new Action(() =>
            {
                this.panel1.Visible = true;
                recSuite = new RecSuite();
                recSuite.Dock = DockStyle.Fill;
                recSuite.FormBorderStyle = FormBorderStyle.None;
                recSuite.TopLevel = false;
                recSuite.OpenMainEvent += RecSuite_OpenMainEvent;
                recSuite.FenxiVideoEvent += RecSuite_FenxiVideoEvent;
                this.panel1.Controls.Clear();
                this.panel1.Controls.Add(recSuite);

                recSuite.Show();

            }));

        }

        private void RecSuite_FenxiVideoEvent()
        {
            this.BeginInvoke(new Action(() =>
            {
                form8 = new Form8();
                form8.Show(this);
                if (this.webBrowser.IsBrowserInitialized)
                {
                    this.webBrowser.ExecuteScriptAsync("GetVideoFrame()");
                }
            }));
        }

        private void RecSuite_OpenMainEvent()
        {
            this.BeginInvoke(new Action(() =>
            {
                recSuite.Close();
                this.panel1.Visible = true;
                mainForm = new FlowForm();
                mainForm.Dock = DockStyle.Fill;
                mainForm.FormBorderStyle = FormBorderStyle.None;
                mainForm.TopLevel = false;
                this.panel1.Controls.Clear();
                this.panel1.Controls.Add(mainForm);

                mainForm.Show();
            }));
        }

        private string SysControl_SaveVideoPathEvent(string arg)
        {
            ConfigNoCacheHelper.AppSettings("VideoPath", arg);
            return "ok";
        }

        private string SysControl_GetVideoPathEvent()
        {
            if (ConfigNoCacheHelper.AppSettings("VideoPath") == "")
            {
                return Application.StartupPath + @"\Resource\ExperimentVideo";
            }
            else
            {
                return ConfigNoCacheHelper.AppSettings("VideoPath");
            }
        }

        private string SysControl_SelectPathEvent()
        {
            string selectPath = "";
            this.Invoke(new Action(() =>
            {
                selectPath = SelectPath("选择保存视频路径");
            }));
            return string.IsNullOrEmpty(selectPath) ? "" : selectPath;
        }

        private void SysControl_CloseFormEvent()
        {
            this.Invoke(new Action(delegate
            {
                this.Close();
            }));
        }

        private void SysControl_MoveFormEvent()
        {
            //this.Invoke(new Action(delegate
            //{
            //    this.MoveForm();
            //}));
        }

        private string SysControl_SaveFileDialogEvent(string title, string defaultFileName)
        {
            string savePath = "";
            this.Invoke(new Action(delegate
            {
                savePath = SaveLocalFile(title, defaultFileName);

            }));
            return savePath;
        }

        private void MyService_HideCameraEvent()
        {
            this.Invoke(new Action(delegate
            {

            }));
        }

        private void MyService_ShowCameraEvent()
        {
            this.Invoke(new Action(delegate
            {

            }));
        }

        private void MyService_InitCameraEvent(string obj)
        {

        }

        private void MyService_StartRecordVideoEvent(string obj, int obj1)
        {
            var videoPath = sysControl.GetVideoPath() + string.Format(@"\{0}\{1}", obj, obj1);
            FileOpera.createPath(videoPath);
            this.Invoke(new Action(() =>
            {

            }));

        }

        private void MyService_StopRecordVideoEvent()
        {

            this.Invoke(new Action(() =>
            {
            }));
        }

        private void WebBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(16000);
                this.Invoke(new Action(() =>
                {

                    this.label1.Visible = false;
                    webBrowser.Visible = true;
                    webBrowser.Focus();
                    //webBrowser.ShowDevTools();
                }));

            });

        }
        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <returns></returns>
        public static string SelectPath(string desc)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.Description = desc;
            if (path.ShowDialog() == DialogResult.OK)
            {
                return path.SelectedPath;
            }
            else
            {
                return "";
            }
        }
        private string SaveLocalFile(string title, string defaultFileName, string filter = "Excel文件|*.xlsx")
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = title;
            saveFileDialog.Filter = filter;
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.FileName = defaultFileName;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                return saveFileDialog.FileName;
            }
            else
            {
                return "";
            }
        }

        public void StartServer()
        {
            p.StartInfo.FileName = @"D:\Program Files\Python34\python.exe";
            p.StartInfo.Arguments = string.Format("{0} {1}", @"D:\WorkData\VS2017Projects\TY_SolidBurningRate\InterfaceServer\runserver.py", "");
            p.StartInfo.UseShellExecute = true;
            p.StartInfo.ErrorDialog = true;
         
            //p.StartInfo.CreateNoWindow = false;
            string strOutput = null;
            try
            {
                p.Start();
                //p.StandardInput.WriteLine(@"python E:\VSProjects2017\TY_SolidBurningRate\InterfaceServer\runserver.py");
                //p.StandardInput.WriteLine("exit");
                //strOutput = p.StandardOutput.ReadToEnd();
                //strOutput = Encoding.UTF8.GetString(Encoding.Default.GetBytes(strOutput));
                //p.WaitForExit();
                //p.Close();
            }
            catch (Exception e)
            {
                strOutput = e.Message;
            }
        }
        /// <summary>
        /// C#里运行Python文件
        /// </summary>
        /// <param name="cmd">要运行的python文件</param>
        /// <param name="args">参数</param>
        public void RunScript(string cmd, string args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"D:\Program Files\Python34-32\python.exe";
            start.Arguments = string.Format("{0} {1}", cmd, args);
            start.UseShellExecute = true;
            start.ErrorDialog = true;

            using (Process process = Process.Start(start))
            {
                process.WaitForExit();
            }
        }
        public void StopServer()
        {
            KillOneProcess("python");


        }
        private static void KillOneProcess(string procName)
        {
            Process[] procs = Process.GetProcesses();//获取已开启的所有进程

            //遍历所有查找到的进程

            for (int i = 0; i < procs.Length; i++)
            {

                //判断此进程是否是要查找的进程
                if (procs[i].ProcessName.ToString().ToLower() == procName)
                {
                    procs[i].Kill();//结束进程
                }
            }


        }
        private void MainCefForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopServer();
        }
    }
}
